package tech.shupi.babytaptv

import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.io.IOException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class ApiModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    override fun getName(): String {
        return "ApiModule"
    }

    private val okHttpClient: OkHttpClient by lazy {
        // 创建一个 TrustManager，用于信任自签名证书
        val trustManagers = arrayOf<TrustManager>(
            object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
                    // 信任所有客户端证书
                }

                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
                    // 信任所有服务器证书
                }

                override fun getAcceptedIssuers(): Array<X509Certificate> {
                    return arrayOf()
                }
            }
        )

        // 创建一个 SSLContext
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, trustManagers, java.security.SecureRandom())

        // 创建 OkHttpClient.Builder 并设置 TLS 协议
        OkHttpClient.Builder()
            .sslSocketFactory(sslContext.socketFactory, trustManagers[0] as X509TrustManager)
            .hostnameVerifier { _, _ -> true }
            .build()
    }

    @ReactMethod
    fun makeRequest(url: String, method: String, headers: ReadableMap?, body: String?, promise: Promise) {
        try {
            val requestBuilder = Request.Builder().url(url)

            // 设置请求方法
            when (method.uppercase()) {
                "GET" -> requestBuilder.get()
                "POST" -> {
                    val mediaType = "application/json; charset=utf-8".toMediaType()
                    requestBuilder.post((body ?: "").toRequestBody(mediaType))
                }
                "PUT" -> {
                    val mediaType = "application/json; charset=utf-8".toMediaType()
                    requestBuilder.put((body ?: "").toRequestBody(mediaType))
                }
                "DELETE" -> requestBuilder.delete()
                else -> requestBuilder.get()
            }

            // 设置请求头
            headers?.toHashMap()?.forEach { (key, value) ->
                requestBuilder.addHeader(key, value.toString())
            }

            val request = requestBuilder.build()
            val call = okHttpClient.newCall(request)

            call.enqueue(object : okhttp3.Callback {
                override fun onFailure(call: Call, e: IOException) {
                    promise.reject("NETWORK_ERROR", e.message, e)
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        val responseBody = response.body?.string() ?: ""
                        val result = Arguments.createMap().apply {
                            putInt("status", response.code)
                            putString("body", responseBody)
                            putString("url", url)
                            putString("method", method)
                        }
                        promise.resolve(result)
                    } catch (e: Exception) {
                        promise.reject("RESPONSE_ERROR", e.message, e)
                    }
                }
            })
        } catch (e: Exception) {
            promise.reject("REQUEST_ERROR", e.message, e)
        }
    }

    @ReactMethod
    fun getCards(url: String, promise: Promise) {
        makeRequest("$url/api/cards", "GET", null, null, promise)
    }

    @ReactMethod
    fun healthCheck(url: String, promise: Promise) {
        makeRequest("$url/health", "GET", null, null, promise)
    }

    @ReactMethod
    fun getImageData(imagePath: String, serverInfo: ReadableMap?, promise: Promise) {
        try {
            android.util.Log.d("ApiModule", "🔍 getImageData 开始 - imagePath: $imagePath, serverInfo: $serverInfo")
            
            // 判断是否为本机数据
            if (imagePath.startsWith("images/")) {
                android.util.Log.d("ApiModule", "📁 检测到本机图片路径: $imagePath")
                // 本机数据，直接读取本地文件
                val imageFile = File(reactApplicationContext.filesDir, imagePath)
                android.util.Log.d("ApiModule", "📂 本地文件路径: ${imageFile.absolutePath}")
                android.util.Log.d("ApiModule", "📂 文件是否存在: ${imageFile.exists()}")
                
                if (imageFile.exists()) {
                    val bytes: ByteArray = imageFile.readBytes()
                    android.util.Log.d("ApiModule", "📊 读取文件成功，大小: ${bytes.size} bytes")
                    val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
                    
                    val result = Arguments.createMap().apply {
                        putString("data", "data:image/jpeg;base64,$base64Data")
                        putInt("size", bytes.size)
                    }
                    android.util.Log.d("ApiModule", "✅ 本机图片加载成功")
                    promise.resolve(result)
                } else {
                    android.util.Log.e("ApiModule", "❌ 本地图片文件不存在: $imagePath")
                    promise.reject("IMAGE_FILE_NOT_FOUND", "本地图片文件不存在: $imagePath")
                }
            } else if (serverInfo == null) {
                android.util.Log.d("ApiModule", "🏠 serverInfo 为 null，尝试从本机数据库查找图片")
                // serverInfo 为 null，说明是本机数据，但路径是远程格式
                // 需要从数据库查找对应的本地文件路径
                
                // 首先尝试直接使用远程路径作为文件名
                val fileName = imagePath.substringAfterLast("/")
                val localImagePath = "images/$fileName"
                android.util.Log.d("ApiModule", "🔍 尝试本地路径: $localImagePath")
                
                val imageFile = File(reactApplicationContext.filesDir, localImagePath)
                android.util.Log.d("ApiModule", "📂 本地文件路径: ${imageFile.absolutePath}")
                android.util.Log.d("ApiModule", "📂 文件是否存在: ${imageFile.exists()}")
                
                if (imageFile.exists()) {
                    val bytes: ByteArray = imageFile.readBytes()
                    android.util.Log.d("ApiModule", "📊 读取文件成功，大小: ${bytes.size} bytes")
                    val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
                    
                    val result = Arguments.createMap().apply {
                        putString("data", "data:image/jpeg;base64,$base64Data")
                        putInt("size", bytes.size)
                    }
                    android.util.Log.d("ApiModule", "✅ 本机图片加载成功（从远程路径转换）")
                    promise.resolve(result)
                } else {
                    // 如果文件不存在，尝试查找 images 目录下的所有文件
                    val imagesDir = File(reactApplicationContext.filesDir, "images")
                    if (imagesDir.exists()) {
                        val files = imagesDir.listFiles()
                        android.util.Log.d("ApiModule", "📂 images 目录下的文件: ${files?.map { it.name }}")
                        
                        // 尝试找到匹配的文件
                        val matchingFile = files?.find { it.name.endsWith(".jpg") || it.name.endsWith(".jpeg") || it.name.endsWith(".png") }
                        if (matchingFile != null) {
                            android.util.Log.d("ApiModule", "🔍 找到匹配的文件: ${matchingFile.name}")
                            val bytes: ByteArray = matchingFile.readBytes()
                            android.util.Log.d("ApiModule", "📊 读取文件成功，大小: ${bytes.size} bytes")
                            val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
                            
                            val result = Arguments.createMap().apply {
                                putString("data", "data:image/jpeg;base64,$base64Data")
                                putInt("size", bytes.size)
                            }
                            android.util.Log.d("ApiModule", "✅ 本机图片加载成功（找到匹配文件）")
                            promise.resolve(result)
                        } else {
                            android.util.Log.e("ApiModule", "❌ 在 images 目录中未找到图片文件")
                            promise.reject("IMAGE_FILE_NOT_FOUND", "在 images 目录中未找到图片文件")
                        }
                    } else {
                        android.util.Log.e("ApiModule", "❌ images 目录不存在")
                        promise.reject("IMAGE_FILE_NOT_FOUND", "images 目录不存在")
                    }
                }
            } else {
                android.util.Log.d("ApiModule", "🌐 检测到远程图片路径: $imagePath")
                // 远程数据，从服务器获取
                val serverUrl = serverInfo.getString("url") ?: throw IllegalArgumentException("缺少服务器URL信息")
                val imageUrl = "$serverUrl/api/images/$imagePath"
                android.util.Log.d("ApiModule", "🔗 构建远程URL: $imageUrl")
                
                val request = Request.Builder()
                    .url(imageUrl)
                    .get()
                    .build()

                val call = okHttpClient.newCall(request)

                call.enqueue(object : okhttp3.Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        android.util.Log.e("ApiModule", "❌ 远程图片加载失败: ${e.message}")
                        promise.reject("IMAGE_LOAD_ERROR", e.message, e)
                    }

                    override fun onResponse(call: Call, response: Response) {
                        try {
                            android.util.Log.d("ApiModule", "📡 远程图片响应状态: ${response.code}")
                            val responseBody = response.body
                            if (response.isSuccessful && responseBody != null) {
                                val bytes = responseBody.bytes()
                                android.util.Log.d("ApiModule", "📊 远程图片数据大小: ${bytes.size} bytes")
                                val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
                                
                                val result = Arguments.createMap().apply {
                                    putString("data", "data:image/jpeg;base64,$base64Data")
                                    putInt("size", bytes.size)
                                }
                                android.util.Log.d("ApiModule", "✅ 远程图片加载成功")
                                promise.resolve(result)
                            } else {
                                android.util.Log.e("ApiModule", "❌ 远程图片响应错误: HTTP ${response.code}")
                                promise.reject("IMAGE_RESPONSE_ERROR", "HTTP ${response.code}")
                            }
                        } catch (e: Exception) {
                            android.util.Log.e("ApiModule", "❌ 远程图片处理错误: ${e.message}")
                            promise.reject("IMAGE_PROCESSING_ERROR", e.message, e)
                        }
                    }
                })
            }
        } catch (e: Exception) {
            android.util.Log.e("ApiModule", "❌ getImageData 异常: ${e.message}")
            promise.reject("IMAGE_REQUEST_ERROR", e.message, e)
        }
    }

    @ReactMethod
    fun getAudioData(audioPath: String, serverInfo: ReadableMap?, promise: Promise) {
        try {
            android.util.Log.d("ApiModule", "🔍 getAudioData 开始 - audioPath: $audioPath, serverInfo: $serverInfo")
            
            // 远程数据，从服务器获取
            val serverUrl = serverInfo?.getString("url") ?: throw IllegalArgumentException("缺少服务器URL信息")
            val audioUrl = "$serverUrl/api/audio/$audioPath"
            android.util.Log.d("ApiModule", "🔗 构建远程URL: $audioUrl")
            
            val request = Request.Builder()
                .url(audioUrl)
                .get()
                .build()

            val call = okHttpClient.newCall(request)

            call.enqueue(object : okhttp3.Callback {
                override fun onFailure(call: Call, e: IOException) {
                    android.util.Log.e("ApiModule", "❌ 远程音频加载失败: ${e.message}")
                    promise.reject("AUDIO_LOAD_ERROR", e.message, e)
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        android.util.Log.d("ApiModule", "📡 远程音频响应状态: ${response.code}")
                        val responseBody = response.body
                        if (response.isSuccessful && responseBody != null) {
                            val bytes = responseBody.bytes()
                            android.util.Log.d("ApiModule", "📊 远程音频数据大小: ${bytes.size} bytes")
                            val base64Data = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
                            
                            val result = Arguments.createMap().apply {
                                putString("data", "data:audio/mpeg;base64,$base64Data")
                                putInt("size", bytes.size)
                            }
                            android.util.Log.d("ApiModule", "✅ 远程音频加载成功")
                            promise.resolve(result)
                        } else {
                            android.util.Log.e("ApiModule", "❌ 远程音频响应错误: HTTP ${response.code}")
                            promise.reject("AUDIO_RESPONSE_ERROR", "HTTP ${response.code}")
                        }
                    } catch (e: Exception) {
                        android.util.Log.e("ApiModule", "❌ 远程音频处理错误: ${e.message}")
                        promise.reject("AUDIO_PROCESSING_ERROR", e.message, e)
                    }
                }
            })
        } catch (e: Exception) {
            android.util.Log.e("ApiModule", "❌ getAudioData 异常: ${e.message}")
            promise.reject("AUDIO_REQUEST_ERROR", e.message, e)
        }
    }
} 